//
//  ProxyArrayController.m
//  Proximator
//
//  Created by Lauri Koskela on 31.7.2011.
//  Copyright (C) 2011 Lauri Koskela
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

#import "ProxyArrayController.h"
#import "ProxyMenuItem.h"
#import "ProximatorAppDelegate.h"

@implementation ProxyArrayController
@synthesize appDelegate;

- (void)awakeFromNib {
    NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    [self setSortDescriptors:[NSArray arrayWithObject:sort]];
    [sort release];
}

- (IBAction)add:(id)sender {
    NSManagedObject *newObject = [self newObject];
    NSString *ID = [[NSProcessInfo processInfo] globallyUniqueString];
    
    [newObject setValue:ID forKey:@"ID"];
    
    ProxyMenuItem *menuItem = [[ProxyMenuItem alloc] init];
    [menuItem bind:@"title" toObject:newObject withKeyPath:@"name" options:nil];
    [menuItem bind:@"ID" toObject:newObject withKeyPath:@"ID" options:nil];
    [menuItem setTarget:appDelegate];
    [menuItem setAction:@selector(selectProxy:)];
    
    [self addObject:newObject];
    [appDelegate.statusMenu insertItem:menuItem atIndex:([[self arrangedObjects] indexOfObject:newObject] + 1)];
    [self fetch:self];
    [newObject release];
    [menuItem release];
}

- (IBAction)remove:(id)sender {
    id obj = [[self selectedObjects] objectAtIndex:0];
    
    NSArray *menuItems = [[appDelegate statusMenu] itemArray];
    for (id menuItem in menuItems) {
        if ([[menuItem ID] isEqualToString:[obj valueForKey:@"ID"]]) {
            [[appDelegate statusMenu] removeItem:menuItem];
            [appDelegate selectProxy:[appDelegate noProxyMenuItem]];
            break;
        }
    }
    [super remove:sender];
}

@end
